package com.woyou.ui.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.EBean.Scope;

import com.citaq.ideliver.R;
import com.umeng.analytics.MobclickAgent;
import com.woyou.bean.FmInfoBean;
import com.woyou.ui.api.BackBan;
import com.woyou.ui.api.IBackEventStrategy;
import com.woyou.ui.api.IKeyEventStrategy;
import com.woyou.ui.fragment.IndexFragment_;
import com.woyou.ui.fragment.MyFragment_;
import com.woyou.ui.fragment.ShopsFragment_;
import com.woyou.ui.fragment.SuperFragment;
import com.woyou.utils.CloneUtils;
import com.woyou.utils.Configure;
import com.woyou.utils.eventbus.EventOpenFM;

import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

/**
 * 封装HomeActivity的逻辑
 * 
 * @author longtao.li
 * 
 */
@EBean(scope = Scope.Singleton)
public class HomeActivityPresenter extends SuperPresenter implements
		OnGestureListener {

	private boolean isAlive = false;

	/** 一级fragment容器 **/
	public static Fragment[] fragments;
	
	/** tab iv控件 **/
	public static ImageView[] imageViews;
	
	private int[] imgIds = new int[] { R.raw.home_index_p, R.raw.home_shops_p,
			R.raw.home_discover_p, R.raw.home_mine_p };
	
	/** 定义手势检测实例 */
	public static GestureDetector detector;
	
	/** 做标签，记录当前是哪个fragment */
	public int MARK = 0;
	
	/** 定义手势两点之间的最小距离 */
	final int DISTANT = 50;

	private FragmentActivity fActivity;

	// private GestureDetector mDetector;

	/** 二级容器fragment的层次关系 **/
	private List<List<Fragment>> containerFms;

	@Override
	public void onCreate(Activity activity) {
		super.onCreate(activity);
		this.fActivity = (FragmentActivity) activity;
		Configure.init(activity);
		initFragment();
		initFoot();
		// 创建手势检测器
		// mDetector = new GestureDetector(mActivity, this);

	}

	public void showFragment(String name) {
		if (!TextUtils.isEmpty(name)) {
			resetTab();
			if (name.equals(IndexFragment_.class.getName())) {
				handlTabClick(0);

			} else if (name.equals(ShopsFragment_.class.getName())) {
				handlTabClick(1);

			} else if (name.equals(MyFragment_.class.getName())) {
				handlTabClick(3);
			}
		}
	}

	/**
	 * 显示非底层fragment
	 * 
	 * @param bean
	 * @param clazz
	 * @param tag
	 */
	@SuppressWarnings({ "unused", "rawtypes" })
	private void showOtherFm(EventOpenFM<Class<Fragment>, FmInfoBean> event) {
		// 深度克隆数据
		FmInfoBean bean = null;
		try {
			bean = (FmInfoBean) CloneUtils.copy((FmInfoBean) event.getBean());
		} catch (ClassNotFoundException e1) {
			Log.e(TAG, "uncaughtException crash", e1);
		} catch (IOException e1) {
			Log.e(TAG, "uncaughtException crash", e1);
		}

		Class<Fragment> clazz = event.getData();
		boolean transparent = event.isTransparent();
		String tag = clazz.getName();
		FragmentManager manager = fActivity.getSupportFragmentManager();
		Fragment fragment = manager.findFragmentByTag(tag);
		FragmentTransaction transaction = manager.beginTransaction();

		if (fragment == null) {
			try {
				fragment = clazz.newInstance();// 反射得到Fragment实例
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
			transaction.add(R.id.home_fm_container, fragment, tag);
		}
		List<Fragment> list = containerFms.get(MARK);// 当前tab的层次关系
		int size = list.size();
		if (size > 0 && !transparent) {
			// //隐藏当前层级最顶层的一个fm
			// Fragment hideFm = list.get(size - 1);
			// transaction.hide(hideFm);
			// 隐藏所有fm
			for (Fragment fm : list) {
				hideFragment(transaction, fm);
				// transaction.hide(fm);
			}
		}
		((SuperFragment) fragment).receiveInfo(bean); // 接收要传递的数据
		if (!list.contains(fragment)) {
			// 将已经显示的fm加入到层级结构中
			Log.i(TAG, "打开" + fragment.getClass().getName());
			list.add(fragment);
		}
		showFragment(fragment, transaction);

		transaction.commitAllowingStateLoss();
	}

	/**
	 * 显示fragment的统一入口
	 * 
	 * @param fragment
	 * @param transaction
	 */
	private void showFragment(Fragment fragment, FragmentTransaction transaction) {
		transaction.show(fragment);
		MobclickAgent.onPageStart(fragment.getClass().getName()); // 统计页面
	}

	/**
	 * 隐藏fragment的统一入口 便于事件统计
	 * 
	 * @param transaction
	 * @param fragment
	 */
	private void hideFragment(FragmentTransaction transaction, Fragment fragment) {
		transaction.hide(fragment);
		MobclickAgent.onPageEnd(fragment.getClass().getName());
	}

	/**
	 * 处理普通的关闭事件
	 * 
	 * @param bean
	 * @param isDestory
	 * @param tag
	 */
	@SuppressWarnings({ "rawtypes", "unused" })
	private void handleEventClose(FmInfoBean bean, boolean isDestory, String tag) {
		FragmentManager manager = fActivity.getSupportFragmentManager();
		FragmentTransaction transaction = manager.beginTransaction();
		List<Fragment> list = containerFms.get(MARK);// 拿到当前页面的层次关系
		Fragment fragment = manager.findFragmentByTag(tag);
		if (fragment != null) {
			if (isDestory) {
				// 隐藏fragment
				// transaction.remove(fragment);
				hideFragment(transaction, fragment);
			} else {
				hideFragment(transaction, fragment);
			}

			Iterator<Fragment> iterator = list.iterator();
			while (iterator.hasNext()) {
				Fragment next = iterator.next();
				if (next.getClass().getName()
						.equals(fragment.getClass().getName())) {
					iterator.remove();
				}
			}

			// if (list.contains(fragment)) {
			// list.remove(fragment);
			// }
			int size = list.size();
			if (size > 0) {
				Fragment fm = list.get(size - 1);
				// 判断是否是查询订单状态Fragment,是则返回底层页面
				if (fm instanceof BackBan) {
					transaction.commitAllowingStateLoss();
					destoryFmStack();
					return;
				}
				String showTag = fm.getClass().getName();
				Fragment showFm = manager.findFragmentByTag(showTag);
				if (showFm == null) {
					showFm = fm;
					transaction.add(R.id.home_fm_container, showFm, showFm
							.getClass().getName());
				}
				((SuperFragment) showFm).receiveInfo(bean); // 接收要传递的数据
				showFragment(showFm, transaction);
			} else {
				((SuperFragment) fragments[MARK]).receiveInfo(bean); // 接收要传递的数据
				// transaction.show(fragments[MARK]);
				showFragment(fragments[MARK], transaction);
				showFrag(MARK);
			}
			transaction.commitAllowingStateLoss();
		}
	}

	/**
	 * 隐藏当前的fragment层级,并显示底层fm
	 */
	private void destoryFmStack() {
		FragmentManager manager = fActivity.getSupportFragmentManager();
		FragmentTransaction transaction = manager.beginTransaction();
		List<Fragment> list = containerFms.get(MARK);// 拿到当前页面的层次关系
		for (Fragment fm : list) {
			Fragment fragment = manager.findFragmentByTag(fm.getClass()
					.getName());
			if (fragment != null) {
				hideFragment(transaction, fragment);
				// transaction.hide(fragment);
			}
		}
		list.clear();
		// transaction.show(fragments[MARK]);
		showFragment(fragments[MARK], transaction);
		transaction.commitAllowingStateLoss();

		showFrag(MARK);
	}

	/**
	 * 隐藏当前的fragment层级
	 */
	@SuppressWarnings("unused")
	private void _destoryFmStack() {
		FragmentManager manager = fActivity.getSupportFragmentManager();
		FragmentTransaction transaction = manager.beginTransaction();
		List<Fragment> list = containerFms.get(MARK);// 拿到当前页面的层次关系
		for (Fragment fm : list) {
			Fragment fragment = manager.findFragmentByTag(fm.getClass()
					.getName());
			if (fragment != null) {
				hideFragment(transaction, fragment);
				// transaction.hide(fragment);
			}
		}
		list.clear();
		transaction.commitAllowingStateLoss();
	}

	/**
	 * 锦囊 用于实施策略,处理硬件返回按钮事件
	 * 
	 * @author longtao.li
	 * 
	 */
	class BackEventHandler {

		IBackEventStrategy strategy;

		public BackEventHandler(IBackEventStrategy strategy) {
			this.strategy = strategy;
		}

		public boolean operate() {
			return strategy.backOperate();
		}

	}

	/**
	 * 锦囊 用于实施策略,处理软键盘按钮事件
	 * 
	 * @author longtao.li
	 * 
	 */
	class KeyEventHandler {

		IKeyEventStrategy strategy;

		public KeyEventHandler(IKeyEventStrategy strategy) {
			this.strategy = strategy;
		}

		public boolean operate(KeyEvent event) {
			return strategy.eventOperate(event);
		}

	}

	/**
	 * 处理软键盘事件
	 * 
	 * @param event
	 * @return
	 */
	public boolean handleKeyEvent(KeyEvent event) {
		List<Fragment> list = containerFms.get(MARK);// 拿到当前页面的层次关系
		int size = list.size();
		if (size == 0) {
			return false;
		}

		Fragment fragment = list.get(size - 1);
		if (fragment instanceof IKeyEventStrategy) {
			// 自行对返回按钮事件进行处理,不交给上层处理
			boolean operate = new KeyEventHandler((IKeyEventStrategy) fragment)
					.operate(event);
			if (operate) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 回退到上一个FM
	 */
	public boolean backFm() {
		List<Fragment> list = containerFms.get(MARK);// 拿到当前页面的层次关系
		int size = list.size();
		if (size == 0) {
			return false;
		}

		Fragment fragment = list.get(size - 1);
		if (fragment instanceof IBackEventStrategy) {
			// 自行对返回按钮事件进行处理,不交给上层处理
			boolean operate = new BackEventHandler(
					(IBackEventStrategy) fragment).operate();
			if (operate) {
				return true;
			}
		}
		FragmentManager manager = fActivity.getSupportFragmentManager();
		FragmentTransaction transaction = manager.beginTransaction();
		hideFragment(transaction, fragment);
		list.remove(fragment);

		size = list.size();
		if (size > 0) {
			// 如果当前层次还有其他Fm,则显示顶层的FM
			Fragment fm = list.get(size - 1);

			// 判断是否是查询订单状态Fragment,是则返回底层页面
			if (fm instanceof BackBan) {
				transaction.commitAllowingStateLoss();
				destoryFmStack();
				return true;
			} else {
				String showTag = fm.getClass().getName();
				Fragment showFm = manager.findFragmentByTag(showTag);
				if (showFm == null) {
					showFm = fm;
					transaction.add(R.id.home_fm_container, showFm, showFm
							.getClass().getName());
				}
				showFragment(showFm, transaction);
			}

		} else {
			// 当前层次没有其他Fm
			// transaction.show(fragments[MARK]);
			showFragment(fragments[MARK], transaction);
			showFrag(MARK);
		}
		transaction.commitAllowingStateLoss();

		return true;
	}

	@Override
	public void onActivityPause() {
		super.onActivityPause();
		isAlive = false;
		// MobclickAgent.onPageEnd(mActivity.getClass().getName());// 保证
		// onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息
		MobclickAgent.onPause(mActivity);
	}

	@Override
	public void onActivityResume(Activity activity) {
		super.onActivityResume(activity);
		isAlive = true;
		// MobclickAgent.onPageStart(mActivity.getClass().getName()); //统计页面
		MobclickAgent.onResume(mActivity); // 统计时长
	}

	/**
	 * 是否显示
	 * 
	 * @return
	 */
	public boolean isAlive() {
		return isAlive;
	}

	@Override
	public void onActivityDestory() {
		super.onActivityDestory();
	}

	/** 初始化fragment */
	public void initFragment() {

		containerFms = new ArrayList<List<Fragment>>();
		containerFms.add(new ArrayList<Fragment>());
		containerFms.add(new ArrayList<Fragment>());
		containerFms.add(new ArrayList<Fragment>());
		containerFms.add(new ArrayList<Fragment>());

		fragments = new Fragment[4];
		fragments[0] = fActivity.getSupportFragmentManager().findFragmentById(
				R.id.indexFragment);
		fragments[1] = fActivity.getSupportFragmentManager().findFragmentById(
				R.id.shopsFragment);
		fragments[2] = fActivity.getSupportFragmentManager().findFragmentById(
				R.id.discoverFragment);
		fragments[3] = fActivity.getSupportFragmentManager().findFragmentById(
				R.id.mineFragment);
		FragmentManager manager = fActivity.getSupportFragmentManager();
		FragmentTransaction transaction = manager.beginTransaction();
		transaction.hide(fragments[0]).hide(fragments[1]).hide(fragments[2])
				.hide(fragments[3]);
		showFragment(fragments[0], transaction);
		// transaction.addToBackStack(null);
		transaction.commitAllowingStateLoss();

	}

	/** 初始化textview */
	public void initFoot() {
		imageViews = new ImageView[4];
		imageViews[0] = (ImageView) mActivity.findViewById(R.id.home_index_iv);
		imageViews[1] = (ImageView) mActivity.findViewById(R.id.home_shops_iv);
		imageViews[2] = (ImageView) mActivity
				.findViewById(R.id.home_discover_iv);
		imageViews[3] = (ImageView) mActivity.findViewById(R.id.home_mine_iv);
		imageViews[0].setImageResource(R.raw.home_index_p);
	}

	/**
	 * tab点击事件
	 * 
	 * @param v
	 */
	public void tabOnclick(View v) {
		resetTab();
		switch (v.getId()) {
		case R.id.home_index_iv:
			handlTabClick(0);
			break;
		case R.id.home_shops_iv:
			handlTabClick(1);
			break;
		case R.id.home_discover_iv:
			handlTabClick(2);
			break;
		case R.id.home_mine_iv:
			handlTabClick(3);
			break;

		default:
			break;
		}
	}

	/** 处理下方导航item的点击事件 **/
	private void handlTabClick(int position) {
		FragmentTransaction transaction = fActivity.getSupportFragmentManager()
				.beginTransaction();
		Fragment showFm;
		showFm = fragments[position];

		// transaction.hide(fragments[0]).hide(fragments[1]).hide(fragments[2])
		// .hide(fragments[3]);
		hideFragment(transaction, fragments[MARK]);
		showFragment(showFm, transaction);
		transaction.commitAllowingStateLoss();
		imageViews[position].setImageResource(imgIds[position]);
		MARK = position;

	}

	/**
	 * 手动调用底层fragment方法通知隐藏行为
	 * 
	 * @param position
	 *            -1为隐藏所有底层frag
	 */
	@SuppressWarnings("unused")
	private void noticeHidden() {
		for (int i = 0; i < fragments.length; i++) {
			hidden(i);
		}
	}

	/**
	 * 通知显示行为
	 * 
	 * @param pos
	 */
	private void showFrag(int pos) {
		fragments[pos].onHiddenChanged(false);
	}

	private void hidden(int pos) {
		fragments[pos].onHiddenChanged(true);
	}

	/** 重置 */
	public void resetTab() {
		imageViews[0].setImageResource(R.raw.home_index);
		imageViews[1].setImageResource(R.raw.home_shops);
		imageViews[2].setImageResource(R.raw.home_discover);
		imageViews[3].setImageResource(R.raw.home_mine);

	}

	/**
	 * activity touch事件
	 * 
	 * @param event
	 * @return
	 */
	// public boolean onTouchEvent(MotionEvent event) {
	// return mDetector.onTouchEvent(event);
	// }

	@Override
	public boolean onDown(MotionEvent e) {
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		// resetTab();
		// // 当是IndexFragment的时候
		// if (MARK == 0) {
		// if (e1.getX() > (e2.getX() + DISTANT)) {// 右滑
		// fActivity.getSupportFragmentManager().beginTransaction()
		// .hide(fragments[0]).hide(fragments[1])
		// .hide(fragments[2]).hide(fragments[3])
		// .show(fragments[1]).commitAllowingStateLoss();
		// imageViews[1].setImageResource(R.raw.home_shops_p);
		// MARK = 1;
		// } else {// 左滑
		// imageViews[0].setImageResource(R.raw.home_index_p);
		// MARK = 0;
		// }
		//
		// }
		// // 当是ShopsFragment的时候
		// else if (MARK == 1) {
		// if (e1.getX() > (e2.getX() + DISTANT)) {// 右滑
		// fActivity.getSupportFragmentManager().beginTransaction()
		// .hide(fragments[0]).hide(fragments[1])
		// .hide(fragments[2]).hide(fragments[3])
		// .show(fragments[2]).commitAllowingStateLoss();
		// imageViews[2].setImageResource(R.raw.home_discover_p);
		// MARK = 2;
		// } else if (e2.getX() > (e1.getX() + DISTANT)) {// 左滑
		// fActivity.getSupportFragmentManager().beginTransaction()
		// .hide(fragments[0]).hide(fragments[1])
		// .hide(fragments[2]).hide(fragments[3])
		// .show(fragments[0]).commitAllowingStateLoss();
		// imageViews[0].setImageResource(R.raw.home_index_p);
		// MARK = 0;
		// } else {// 不滑
		// imageViews[1].setImageResource(R.raw.home_shops_p);
		// MARK = 1;
		// }
		// }
		// // 当是DiscoverFragment的时候
		// else if (MARK == 2) {
		// if (e1.getX() > (e2.getX() + DISTANT)) {// 右滑
		// fActivity.getSupportFragmentManager().beginTransaction()
		// .hide(fragments[0]).hide(fragments[1])
		// .hide(fragments[2]).hide(fragments[3])
		// .show(fragments[3]).commitAllowingStateLoss();
		// imageViews[3].setImageResource(R.raw.home_mine_p);
		// MARK = 3;
		// } else if (e2.getX() > (e1.getX() + DISTANT)) {// 左滑
		// fActivity.getSupportFragmentManager().beginTransaction()
		// .hide(fragments[0]).hide(fragments[1])
		// .hide(fragments[2]).hide(fragments[3])
		// .show(fragments[1]).commitAllowingStateLoss();
		// imageViews[1].setImageResource(R.raw.home_shops_p);
		// MARK = 1;
		// } else {
		// imageViews[2].setImageResource(R.raw.home_discover_p);
		// MARK = 2;
		// }
		// }
		// // 当是MineFragment的时候
		// else if (MARK == 3) {
		// if (e2.getX() > (e1.getX() + DISTANT)) {
		// fActivity.getSupportFragmentManager().beginTransaction()
		// .hide(fragments[0]).hide(fragments[1])
		// .hide(fragments[2]).hide(fragments[3])
		// .show(fragments[2]).commitAllowingStateLoss();
		// imageViews[2].setImageResource(R.raw.home_discover_p);
		// MARK = 2;
		// } else {
		// imageViews[3].setImageResource(R.raw.home_mine_p);
		// MARK = 3;
		// }
		// }
		return false;
	}

}
